/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.core.commands;

import java.util.List;

import org.eclipse.gef.commands.Command;

import com.cea.papyrus.core.helper.ModelerHelper;
import com.cea.papyrus.diagraminterchange2.di2.GraphNode;
import com.cea.papyrus.diagraminterchange2.di2.Uml1SemanticModelBridge;


/**
 * Add a Feature as the child of a FeatureList.
 * 
 * @author dumoulin
 */
public class FeatureAddChildCommand extends Command {

	/**
	 * 
	 */
	private Object child;
	
	/**
	 * 
	 */
	private Object after;
	
	/**
	 * 
	 */
	private List list;  
	
	/**
	 * 
	 */
	private GraphNode gparent;//graphNode for the class
	
	/**
	 * 
	 */
	private GraphNode parent;
	
	/**
	 * 
	 * 
	 * @param child 
	 * @param featureList 
	 * @param after 
	 */
	public FeatureAddChildCommand(GraphNode featureList, Object child, Object after ) {
		
		this.list=featureList.getContained();
		gparent=(GraphNode)featureList.getContainer();
		this.child = child;
		this.after = after;
		this.parent=featureList;
		
	}

		/**
		 * 
		 * 
		 * @return 
		 */
		@Override
		public boolean canExecute() {
		
		if( (list ==null) || (child==null)){return false;}
		if(((GraphNode)child).getSemanticModel()==null ){return false;}
		Class umlChild= ((Uml1SemanticModelBridge)((GraphNode)child).getSemanticModel()).getElement().getClass().getInterfaces()[0];
		return ModelerHelper.getFactory().canCreateGraphElement(umlChild, parent);
		
		}

	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#execute()
	 */
	/**
	 * 
	 */
	@Override
	public void execute() {
		
		//The Uml Element parent is the linked to the graphNode greatParent.
		//Manager.getRessourceManager().toConnect(gparent, (GraphNode)child);
		redo();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#redo()
	 */
	/**
	 * 
	 */
	@Override
	public void redo() {
		// Compute the index here because Command can be called twice.
		int atPos = list.indexOf(after);
		
				
		if( after == null )
		{ // Add at end
		    list.add(child);
		}
		else 
		{ 
			list.add(atPos, child);
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.gef.commands.Command#undo()
	 */
	/**
	 * 
	 */
	@Override
	public void undo() {
		list.remove(child);
	}
	
	
}
